<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加文章</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert
        title="添加考试/小测信息"
        type="info"
        show-icon
        center
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex * 1" align-center>
        <el-step title="文章信息"></el-step>
        <el-step title="文章内容"></el-step>
        <el-step title="文章图片"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签导航区域 选中那个就会自动将对应name属性值绑定到v-model中 -->
      <el-form
        label-position="top"
        :model="addForm"
        ref="addRuleForm"
        label-width="100px"
      >
        <!-- :before-leave="beforeTabLeave"
          @tab-click="tabClick" -->
        <el-tabs tab-position="left" v-model="activeIndex">
          <el-tab-pane label="文章信息" name="0">
            <el-form-item label="标题" prop="">
              <el-input
                v-model="addForm.articleDetailVo.articleTitle"
              ></el-input>
            </el-form-item>
            <el-form-item label="作者" prop="">
              <el-input
                v-model="addForm.articleDetailVo.articleAuthor"
              ></el-input>
            </el-form-item>
            <el-form-item label="标签" prop="">
              <el-input v-model="tags"></el-input>
            </el-form-item>
            <!-- <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addForm.goods_number"></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="商品分类" prop="goods_name"> -->
            <!-- 级联选择器     -->
            <!-- <el-cascader
                v-model="cateSelected"
                :options="cateList"
                :props="cateProps"
                clearable
                @change="handleCateChange"
              >
              </el-cascader>
            </el-form-item> -->
          </el-tab-pane>
          <el-tab-pane label="文章内容" name="1">
            <!-- 富文本编辑器 -->
            <!-- <el-upload
              drag
              multiple
              :headers="headerObj"
              class="quill-upload"
              :on-success="quillSuccess"
              :action="uploadUrl"
            > -->
            <!-- <el-button size="small" type="primary">点击上传</el-button> -->
            <!-- <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload> -->
            <quill-editor
              v-model="addForm.articleDetailVo.articleContent"
              ref="myQuillEditor"
            ></quill-editor>
          </el-tab-pane>
          <el-tab-pane label="文章配图" name="2">
            <!-- 上传图片区域 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              list-type="picture-card"
              :headers="headerObj"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :file-list="fileList"
              :show-file-list="true"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    @click="handleRemove(file)"
                    class="el-upload-list__item-delete"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="添加文章" name="3">
            <el-button type="primary" @click="addText" class="addBtn"
              >添加文章</el-button
            >
          </el-tab-pane>
          <!-- <el-tab-pane label="商品属性" name="3"> -->
          <!-- 静态属性列表 -->
          <!-- <el-form-item
              :label="item.attr_name"
              v-for="(item, i) in onlyParamsList"
              :key="i"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane> -->

          <!-- <el-tab-pane label="商品内容" name="4"> -->
          <!-- 富文本编辑器 -->
          <!-- <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods" class="addBtn"
              >添加商品</el-button
            > -->
          <!-- </el-tab-pane> -->
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    const toolbarOptions = [
      ["bold", "italic", "underline", "strike"], // toggled buttons
      ["blockquote", "code-block"],

      [{ header: 1 }, { header: 2 }], // custom button values
      [{ list: "ordered" }, { list: "bullet" }],
      [{ script: "sub" }, { script: "super" }], // superscript/subscript
      [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
      [{ direction: "rtl" }], // text direction

      [{ size: ["small", false, "large", "huge"] }], // custom dropdown
      [{ header: [1, 2, 3, 4, 5, 6, false] }],

      [{ color: [] }, { background: [] }], // dropdown with defaults from theme
      [{ font: [] }],
      [{ align: [] }],
      ["link", "image", "video"],
      ["clean"] // remove formatting button
    ];
    return {
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              // 重写点击组件上的图片按钮要执行的代码
              image: function(value) {
                document.querySelector(".quill-upload .el-icon-upload").click();
              }
            }
          }
        }
      },

      //   选择考试还是小测
      options: [
        {
          value: "1",
          label: "考试"
        },
        {
          value: "2",
          label: "小测"
        }
      ],
      value: "1",
      // 问题列表
      questionList: [],
      // tab页签激活值
      activeIndex: "0",
      // 总数
      total: "",
      //   添加表单
      tags: "",
      addForm: {
        articleDetailVo: {
          articleAuthor: "",
          articleContent: "",
          articleImg: "",
          articleTitle: ""
        },
        tagList: []
      },
      //   添加校验规则
      addRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          { type: "number", message: "价格必须为数字值" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
          { type: "number", message: "重量必须为数字值" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
          { type: "number", message: "数量必须为数字值" }
        ]
      },
      //   分类数据
      cateList: [],
      //   级联选择器属性
      cateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      cateSelected: [],
      //   动态参数列表
      manyParamsList: [],
      //   静态属性列表
      onlyParamsList: [],
      //   上传图片
      dialogImageUrl: "",
      //   上传图片列表
      fileList: [],
      dialogVisible: false,
      disabled: false,
      //   为上传图片添加token
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 图片上传接口
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload"
    };
  },
  methods: {
    // 多选勾选时将对应questionId添加到删除序列
    handleSelectionChange(rows) {
      //   console.log(rows);
      this.addForm.qidList = [];
      rows.forEach(item => {
        this.addForm.qidList.push(item.questionId);
      });
      console.log(this.addForm.qidList);
    },
    // 图片处理
    quillSuccess(response) {
      if (response) {
        // 获取文本编辑器
        const quill = this.$refs.myQuillEditor.quill;
        // 获取光标位置
        const pos = quill.getSelection().index;
        // 插入图片到光标位置
        quill.insertEmbed(pos, "image", response.data.url);
      } else {
        this.$essage.error("图片插入失败");
      }
    },
    // 添加文章
    async addText() {
      this.$refs.addRuleForm.validate(async valid => {
        if (!valid) return this.$message.error("请填写必要的信息！");
        this.addForm.tagList.push(this.tags);
        const { data: res } = await this.$http.post(
          "article/addArticle",
          this.addForm
        );
        console.log(res);
        this.$message.success("添加文章成功！");
        this.$router.push("/text");
      });
    },
    // 监听级联选择器改变
    handleCateChange() {
      console.log(this.cateSelected);
      if (this.cateSelected.length !== 3) {
        this.cateSelected = [];
        this.$message.info("只允许选中第三级分类！");
      } else {
        this.addForm.goods_cat = this.cateSelected.join(",");
        console.log(this.addForm.goods_cat);
      }
    },
    // 移除图片
    handleRemove(file) {
      console.log(file);
      const i = this.addForm.pics.findIndex(
        x => x.pic === file.response.data.tmp_path
      );
      this.addForm.pics.splice(i, 1);
      console.log(this.addForm.pics);
      // 删除
      for (let key in file) {
        delete file[key];
      }
    },
    // 查看上传图片大图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片上传成功
    handleSuccess(res) {
      const item = { pic: res.data.tmp_path };
      this.addForm.pics.push(item);
      this.$message.success("图片上传成功！");
      console.log(this.addForm.pics);
    }
  },
  computed: {
    cateId() {
      if (this.cateSelected.length === 3) {
        return this.cateSelected[2];
      }
      return null;
    }
  },
  created() {}
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0;
}
.el-tabs {
  margin: 40px 0;
}
.addBtn {
  margin-top: 20px;
}
</style>